﻿using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace DisplayDemo
{
    public class MainWindowViewModel : BindableBase
    {
        //基础的通知属性
        private string _value = "12121212121";

        public string Value
        {
            get { return _value; }
            set
            {
                //第一种方式
                SetProperty<string>(ref _value, value);

                //第二种方式
                //RaisePropertyChanged(nameof(Value));

                //第三种方式
                //this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs(nameof(Value)));
            }
        }

        public MainWindowViewModel(FrameDispatcher dispatcher)
        {
            _ = WriteCameraFrames(dispatcher);
            ImageData imageData = GetBitmap(@"C:\Users\Administrator\Desktop\20250313 143022.png");

            dispatcher.Dispatch(imageData, 0);
        }

        async Task WriteCameraFrames(FrameDispatcher dispatcher)
        {
            uint id = 0;
            uint lastFocusFrame = 0;
            using var sub = dispatcher.Frames;
            for (; ; )
            {
                var (img, frameData) = await sub.Read();
                if (img != null)
                {
                    
                }
            }
        }

        ImageData GetBitmap(string path)
        {
            // 读取文件
            using var stream = new FileStream(path, FileMode.Open);
            var decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            // 获取第一帧（对于大多数情况下的单帧图像如PNG来说足够了）
            var bitmapSource = decoder.Frames[0];

            // 确保是Gray8格式
            if (bitmapSource.Format != PixelFormats.Gray8)
            {
                throw new NotSupportedException("仅支持灰度8位图像格式");
            }

            // 读取图像宽度和高度
            int width = bitmapSource.PixelWidth;
            int height = bitmapSource.PixelHeight;

            // 准备存储像素数据的字节数组
            int stride = width; // 对于Gray8, 每行的字节数等于宽度
            byte[] data = new byte[height * stride];

            // 将像素数据复制到位数组中
            bitmapSource.CopyPixels(data, stride, 0);

            return new ImageData(width, height, data, PixelFormats.Gray8);
        }
    }
}
